import { select } from "d3-selection";
import { cumsum } from "d3-array";
import { axisLeft, axisRight } from "d3-axis";

// 初始化tool tip
function initToolTip(className) {
  let tooltip = select(`.${className}`);
  if (!tooltip.node()) {
    tooltip = select(document.createElement("div")).call(function (el) {
      el.attr("class", className)
        .style("position", "absolute")
        .style("pointer-events", "none")
        .style("top", 0)
        .style("left", 0)
        .style("display", "none")
        .style("background-color", "rgb(240 240 240 / 70%)")
        .style("border-radius", "5px")
        .style("box-shadow", "0 0 10px rgba(0,0,0,.25)")
        .style("padding", "10px")
        .style("line-height", "1.3")
        .style("font-size", "14px");
    });
  }
  return tooltip;
}

// 横向图例
function swatches({
  svg,
  colour,
  swatchWidth = 15,
  swatchHeight = swatchWidth,
  swatchPadding = (swatchWidth / 2) * (2 / 3),
  labelPadding = swatchWidth * 0.75,
  marginTop = 0,
  marginLeft = 0,
} = {}) {
  const spacing = colour
    .domain()
    .map((d) => getTextWidth(d) + swatchWidth + swatchPadding + labelPadding)
    .map((_, i, g) => cumsum(g)[i]);

  const height = swatchHeight + swatchPadding * 2;

  const g = svg
    .append("g")
    .attr("transform", `translate(${marginLeft}, ${height / 2 + marginTop})`)
    .selectAll("g")
    .data(colour.domain())
    .join("g")
    .attr("transform", (d, i) => `translate(${spacing[i - 1] || 0}, 0)`);

  g.append("rect")
    .attr("fill", colour)
    .attr("width", swatchWidth)
    .attr("height", swatchHeight)
    .attr("y", -swatchHeight / 2);

  g.append("text")
    .attr("x", swatchWidth + swatchPadding)
    .attr("y", 0)
    .attr("dominant-baseline", "central")
    .text((d) => d);
}

// 获取文本宽度
function getTextWidth(label) {
  const svg = select(document.body).append("svg");
  svg.append("g").append("text").text(label);

  const width = svg.node().getElementsByTagName("g")[0].getBBox().width;

  svg.remove();

  return width;
}

// 设置矩形最小宽度（矩形方向为横向）或最小高度（矩形方向为纵向）
function setRectMinWidthOrHeight(rectWidthOrHeight) {
  if (rectWidthOrHeight > 0 && rectWidthOrHeight < 5) {
    return 5;
  }
  return rectWidthOrHeight;
}

// 获取y轴宽度
function getYAxisWidth({
  yScale,
  height,
  margin,
  axisDirection = "left",
  fontSize = 14,
}) {
  const svg = select(document.body).append("svg");

  yScale.range([height - margin.bottom, margin.top]);
  const yAxis = (g) =>
    g
      .call(axisDirection === "left" ? axisLeft(yScale) : axisRight(yScale))
      .selectAll("g")
      .attr("font-size", fontSize);
  svg.append("g").call(yAxis);

  let yAxisWidth = svg.node().getElementsByTagName("g")[0].getBBox().width;
  yAxisWidth = yAxisWidth > margin.left ? yAxisWidth : margin.left;

  svg.remove();
  return yAxisWidth;
}

export { initToolTip, swatches, setRectMinWidthOrHeight, getYAxisWidth };
